<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button-group>
          <a-button type="primary" @click="add()">添加班级</a-button>
        </a-button-group>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-form :inline="true" size="mini">
          <el-form-item label="班级名称">
            <el-input v-model="mname" placeholder="班级名称"></el-input>
          </el-form-item>
          <el-form-item label="校区">
            <el-select v-model="search" placeholder="校区">
              <el-option label="全部校区" value></el-option>
              <el-option
                v-for="(item, i) in getschooladdress"
                :key="`1inline${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程">
            <el-select v-model="mcourse" placeholder="课程">
              <el-option label="取消选择" value></el-option>
              <el-option
                v-for="(item, i) in schoolcourse"
                :key="`2inline${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
          style="width: 100%; border: 1px solid #eeeeee"
        >
          <el-table-column prop="ID" label="序号" width="60">
            <template slot-scope="scope">{{scope.$index+1}}</template>
          </el-table-column>
          <el-table-column prop="name" label="班级名称" width="180">
            <template slot-scope="scope">
              <el-button
                type="text"
                v-text="scope.row.name"
                @click="watchthis = true ; index = scope.row.ID"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column prop="type" sortable label="人数">
            <template slot-scope="scope">
              <router-link
                :to="{name:'班级学员', params: { ID: scope.row.ID }}"
              >{{getstudentnum(scope.row.ID)}} / {{ scope.row.studentnum }}</router-link>
            </template>
          </el-table-column>
          <el-table-column prop="info" label="所在校区">
            <template
              slot-scope="scope"
            >{{ getschooladdressbyid( scope.row.schooladdressid).name }}</template>
          </el-table-column>
          <el-table-column prop="studentnum" sortable label="课程">
            <template
              slot-scope="scope"
            >{{ scope.row.schoolcourseid?getschoolcoursebyid( scope.row.schoolcourseid).name:'' }}</template>
          </el-table-column>
          <el-table-column prop="type" sortable label="开班日期" width="120px">
            <template slot-scope="scope">{{ totime(scope.row.starttime) }}</template>
          </el-table-column>
          <el-table-column prop="studentnum" sortable label="结课日期" width="120px">
            <template slot-scope="scope">{{ totime(scope.row.endtime) }}</template>
          </el-table-column>
          <el-table-column prop="studentnum" sortable label="开班状态" width="120px">
            <template slot-scope="scope">{{ types[scope.row.type] }}</template>
          </el-table-column>
          <el-table-column align="right" width="100px">
            <template slot-scope="scope">
              <el-dropdown trigger="click" @command="command">
                <el-button size="small" type="primary">
                  操作
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    class="bg-primary text-white"
                    icon="el-icon-setting"
                    :command="{f:add, d:  scope.row}"
                    v-show="scope.row.type !== '0'"
                  >编辑</el-dropdown-item>

                  <el-dropdown-item
                    class="bg-info text-white"
                    :command="{f:push, d:  {name:'课程安排', params: { ID: scope.row.ID }}}"
                    icon="el-icon-s-operation"
                    v-show="scope.row.type !== '0'"
                  >排课</el-dropdown-item>
                  <el-dropdown-item
                    icon="el-icon-s-home"
                    class="bg-dark text-white"
                    :command="{f:changes, d:  scope.row.ID}"
                    v-show="scope.row.type !== '0'"
                  >结课</el-dropdown-item>
                  <el-dropdown-item
                    class="bg-danger text-white"
                    icon="el-icon-delete"
                    :command="{f:del, d:  scope.row.ID}"
                  >删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          @current-change="currentChange"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="tableData.length"
        ></el-pagination>
        <el-dialog class="school-form" :title="title" width="510px" :visible.sync="setaddress">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini">
            <el-form-item label="班级名称:" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="所在校区:" prop="schooladdressid">
              <el-select v-model="ruleForm.schooladdressid" allow-create placeholder="请选择校区">
                <el-option
                  v-for="(item, i) in getschooladdress"
                  :key="`1class${i}`"
                  :label="item.name"
                  :value="item.ID"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="满班人数:" prop="studentnum">
              <el-input-number v-model="ruleForm.studentnum" :min="1" :max="1000"></el-input-number>
            </el-form-item>
            <el-form-item label="开班日期:">
              <el-date-picker v-model="ruleForm.starttime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="结课日期:">
              <el-date-picker v-model="ruleForm.endtime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="课程:">
              <el-select v-model="ruleForm.schoolcourseid" allow-create placeholder="选择课程">
                <el-option
                  v-for="(item, i) in getcourse"
                  :key="`2class${i}`"
                  :label="item.name"
                  :value="item.ID"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
            <el-button @click="setaddress = false" size="mini">取 消</el-button>
          </div>
        </el-dialog>
        <el-dialog class="school-form" title="班级详情" width="510px" :visible.sync="watchthis">
          <el-form class="htedialogtext" v-if="watchthis" label-width="150px" size="mini">
            <el-form-item label="班级名称:">
              <span v-text="scope.name"></span>
            </el-form-item>
            <el-form-item label="所在校区:">
              <span v-text="getschooladdressbyid( scope.schooladdressid).name"></span>
            </el-form-item>
            <el-form-item label="人数（招生/满班）:">
              <span>{{getstudentnum(scope.ID)}} / {{ scope.studentnum }}</span>
            </el-form-item>
            <el-form-item label="班级状态:">
              <span>{{ types[scope.type] }}</span>
            </el-form-item>
            <el-form-item label="开班日期:">
              <span>{{ totime(scope.starttime) }}</span>
            </el-form-item>
            <el-form-item label="结课日期:">
              <span>{{totime(scope.endtime) }}</span>
            </el-form-item>
            <el-form-item label="课程:">
              <span>{{ scope.schoolcourseid?getschoolcoursebyid( scope.schoolcourseid).name:'' }}</span>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="watchthis = false" type="primary" plain size="mini">返回</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  asynccreateschoolclazz,
  asyncdelschoolclazz,
  asyncchangeschoolclazztype
} from "../../../../plugins/api.js";
import { totime } from "../../../utils.js";
export default {
  name: "class",
  data() {
    return {
      mname: "",
      mcourse: "",
      watchthis: false,
      index: 0,
      isaddress: true,
      setaddress: false,
      checkList: [],
      search: "",
      currentPage: 1,
      pagesize: 10,
      title: "添加班级",
      ruleForm: {
        ID: "",
        name: "",
        starttime: "",
        endtime: "",
        studentnum: "",
        schoolcourseid: "",
        schooladdressid: ""
      },
      resource: true,
      rules: {
        name: [
          { required: true, message: "请输入班级名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        schooladdressid: [
          { required: true, message: "请选择校区", trigger: "change" }
        ],
        studentnum: [
          { required: true, message: "请输入班级名称", trigger: "blur" }
        ],
        starttime: [
          { required: true, validator: this.isstarttime, trigger: "blur" }
        ],
        endtime: [
          { required: true, validator: this.isendtime, trigger: "blur" }
        ]
      },
      types: {
        "1": "未排课",
        "2": "已排课",
        "3": "已开班",
        "0": "已结课"
      }
    };
  },
  computed: {
    ...mapGetters([
      "getschoolcourse",
      "getschooladdress",
      "getschoolclazz",
      "getschool",
      "getschooladdressbyid",
      "getschoolcoursebyid"
    ]),
    tableData() {
      const { getschoolclazz, search, mname, mcourse } = this;
      return getschoolclazz.filter(data => {
        const x = search ? data.schooladdressid == search : true;
        const y = mname ? data.name.includes(mname) : true;
        const z = mcourse ? data.schoolcourseid == mcourse : true;
        return x && y && z;
      });
    },
    scope() {
      return this.getschoolclazz.find(v => v.ID === this.index);
    },
    getcourse() {
      return this.getschoolcourse.filter(v => {
        if (v.type == "停售") return;
        if (v.addressids) {
          return true;
        } else {
          const x = v.addressids.split(",");
          return x.includes(this.ruleForm.schooladdressid);
        }
      });
    },
    schoolcourse() {
      return this.getschoolcourse.filter(v => {
        if (v.type == "停售") return;
        if (v.addressids) {
          return true;
        } else {
          const x = v.addressids.split(",");
          return x.includes(this.search);
        }
      });
    }
  },
  mounted() {
    if (this.getschooladdress.length) {
      this.isaddress = false;
    }
  },
  watch: {
    "ruleForm.schooladdressid"() {
      this.ruleForm.schoolcourseid = "";
    }
  },
  methods: {
    command({ f, d }) {
      f(d);
    },
    push(v) {
      this.$router.push(v);
    },
    totime,
    getstudentnum(id) {
      const { schoolstudentschoolclazz } = this.getschoolclazz.find(
        v => v.ID == id
      );
      return schoolstudentschoolclazz.filter(v => v.type === "在读").length;
    },
    currentChange(index) {
      this.currentPage = index;
    },
    add(v) {
      this.setaddress = true;
      if (v) {
        this.title = "修改班级";
        this.ruleForm = JSON.parse(JSON.stringify(v));
      } else {
        this.title = "添加班级";
        this.ruleForm = {
          name: "",
          starttime: "",
          endtime: "",
          studentnum: "",
          schoolcourseid: "",
          schooladdressid: ""
        };
      }
    },
    del(ID) {
      this.$confirm("此操作将永久删除该班级, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await asyncdelschoolclazz({ ID });
            await this.$store.dispatch("actionschoolclazz");
            this.$message.success("删除成功");
          } catch (err) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    changes(ID) {
      this.$confirm(`此该班级设置成结课, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await asyncchangeschoolclazztype({ ID, type: 0 });
            await this.$store.dispatch("actionschoolclazz");
            this.$message.success(`结课成功`);
          } catch (err) {
            this.$message.error(`结课失败`);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    async submitForm() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          const data = this.ruleForm.ID ? "修改" : " 添加";
          try {
            await asynccreateschoolclazz(this.ruleForm);
            await this.$store.dispatch("actionschoolclazz");
            this.setaddress = false;
            this.$message.success(`${data}成功`);
          } catch (err) {
            this.$message.error(`${data}失败`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.dialog-footer {
  text-align: center;
}
</style>